package gogsci

import "sync"

type Store interface {
	SaveResult(payload *PushPayload, result *Result)
	FindByRepo(fullName string) []Result
	FindById(id string) Result
}

type Result struct {
	Id       string
	FullName string
	Status   int
	Message  string
	Error    string
	RepoInfo *PushPayload
}

type MemoryStore struct {
	results map[*PushPayload]*Result
	mu      sync.RWMutex
}

func (m *MemoryStore) SaveResult(payload *PushPayload, result *Result) {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.results[payload] = result
}

func (m *MemoryStore) FindByRepo(fullName string) []Result {
	m.mu.RLock()
	defer m.mu.RUnlock()

	var res = make([]Result, 0)
	for _, r := range m.results {
		if r.FullName == fullName {
			res = append(res, *r)
		}
	}

	return res
}

func (m *MemoryStore) FindById(id string) Result {
	m.mu.RLock()
	defer m.mu.RUnlock()

	for _, r := range m.results {
		if r.Id == id {
			return *r
		}
	}
	return Result{}
}

func NewMemoryStore() Store {
	m := new(MemoryStore)
	m.results = make(map[*PushPayload]*Result)
	return m
}
